package com.dingding.service.systemservice.impl;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.bean.databean.response.DataResponse;
import com.dingding.bean.entity.SystemKey;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.encrpt.RSACoder;
import com.dingding.service.BaseService;
import com.dingding.service.systemservice.ISystemKeyService;
import com.dingding.util.SystemKeyValue;

/**
 * @ClassName: SystemKeyServiceImpl
 * @author cheshaowei
 * @date 2015-10-27 下午07:39:13
 */
public class SystemKeyServiceImpl extends BaseService implements
		ISystemKeyService {

	private static final Logger log = Logger.getLogger(SystemKeyServiceImpl.class);

	/**
	 * 
	 * @Title: setEncrptKey
	 * @Description:初始化加密秘钥
	 * @author cheshaowei
	 * @throws
	 */
	@Override
	@Transactional(readOnly=true)
	public void initalEncrptKey() {

		
		SystemKey systemKey = null;
		try {
			
			systemKey = systemKeyDao.getSystemKey();
			
		} catch (Exception e) {
			log.error("获取系统秘钥出现异常,退出虚拟机！",e);
			System.exit(0);
		}

		if (systemKey != null
				&& ToolUtil.isNotBlank(systemKey.getClientPublicKey())
				&& ToolUtil.isNotBlank(systemKey.getServerPrivateKey())) {
			
			// 初始化秘钥
			log.info("秘钥读取成功！");
			//公钥，加密数据用
			SystemKeyValue.CLIENT_PUBLIC_KEY = systemKey.getServerPublicKey();
			//私钥，解密数据用
			SystemKeyValue.SERVER_PRIVATE_KEY = systemKey.getServerPrivateKey(); 
			
		} else {
			
			// 退出虚拟机
			log.error("秘钥读取失败，程序退出！");
			System.exit(0);
			
		}

	}
	
	
	/**
	 * @Title: addEncrptKey 
	 * @Description:初始化秘钥到数据库
	 * @author cheshaowei
	 * @throws
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public SystemKey addEncrptKey(){
		
		SystemKey systemKey = new SystemKey();
		
		try {
			//生成客户端公钥和私钥
			Map<String, Object> keyMap = RSACoder.initKey();
			// 客户端公钥
			systemKey.setClientPublicKey(RSACoder.getPublicKey(keyMap));
			// 客户端私钥
			systemKey.setClientPrivateKey(RSACoder.getPrivateKey(keyMap));
			
			//生成服务端公钥和私钥
			keyMap = RSACoder.initKey();
			// 服务端端公钥
			systemKey.setServerPublicKey(RSACoder.getPublicKey(keyMap));
			// 服务端私钥
			systemKey.setServerPrivateKey(RSACoder.getPrivateKey(keyMap));
			
			super.systemKeyDao.addSystemKey(systemKey);
			
		} catch (Exception e) {
			log.error("初始化秘钥到数据库出现异常！",e);
		}
		return systemKey;
	}
	

	@Override
	public void setStatus(DataResponse dataResponse, int status) {

	}

}
